package com.lifesea.notify.push;

import com.lifesea.base.entity.PushAppEnums;
import com.lifesea.base.entity.PushRequest;
import com.lifesea.base.entity.PushResponse;
import com.lifesea.base.entity.ResultEnum;
import com.lifesea.commons.exception.ErrorCodeConst;
import com.lifesea.commons.exception.ErrorCodeException;
import com.lifesea.conifg.IosPushConfig;
import com.lifesea.model.SysDeviceIdentify;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * Ios push
 * User: chendw
 * Date: 2016/7/19 13:44
 * To change this template use File | Settings | File Templates.
 */
@Component
public class IosPushService implements IPushService {

    private final Logger logger = LoggerFactory.getLogger(IosPushService.class);

    private static final String IOS_CERTIFICATE_PATH = "/ios/";

    public IosPushService() {

    }

    @Override
    public PushResponse send(PushRequest pushRequest, SysDeviceIdentify deviceIdentify) {

        PushNotificationPayload payLoad = new PushNotificationPayload();
        PushResponse response = new PushResponse();
        try {
            payLoad.addAlert(pushRequest.getBody()); // 消息内容
            if (pushRequest.getCategory() != null) {
                payLoad.addCustomDictionary("category", pushRequest.getCategory());
            }
            if (StringUtils.isNotBlank(pushRequest.getRefId())) {
                payLoad.addCustomDictionary("ref_id", pushRequest.getRefId());
                payLoad.addCustomDictionary("refId", pushRequest.getRefId());   // 兼容老版本
            }
            if (pushRequest.getRefType() != null) {
                payLoad.addCustomDictionary("refType", pushRequest.getRefType());
                payLoad.addCustomDictionary("ref_type", pushRequest.getRefType());
            }
            if (StringUtils.isNotBlank(pushRequest.getUrl())) {
                payLoad.addCustomDictionary("url", pushRequest.getUrl());
            }

            if (!StringUtils.isBlank(pushRequest.getSound())) {
                payLoad.addSound(pushRequest.getSound());   //铃音
            }

            PushNotificationManager pushNotificationManager;
            InputStream keystore;
            if (StringUtils.equals(PushAppEnums.resident.value(), deviceIdentify.getAppcode())) { // 居民
                pushNotificationManager = new PushNotificationManager();
                keystore = IosPushService.class.getResourceAsStream(IOS_CERTIFICATE_PATH + IosPushConfig.PUSH_RESIDENT_FILE);
                pushNotificationManager.initializeConnection(new AppleNotificationServerBasicImpl(keystore, IosPushConfig.PUSH_RESIDENT_PASSWORD, IosPushConfig.PUSH_RESIDENT_PUSH_PRODUCTIO));
            } else if (StringUtils.equals(PushAppEnums.family_doctor.value(), deviceIdentify.getAppcode())) { // 家医
                pushNotificationManager = new PushNotificationManager();
                keystore = IosPushService.class.getResourceAsStream(IOS_CERTIFICATE_PATH + IosPushConfig.PUSH_FAMILYDOCTOR_FILE);
                pushNotificationManager.initializeConnection(new AppleNotificationServerBasicImpl(keystore, IosPushConfig.PUSH_FAMILYDOCTOR_PASSWORD, IosPushConfig.PUSH_FAMILYDOCTOR_PUSH_PRODUCTIO));
            } else if (StringUtils.equals(PushAppEnums.major_doctor.value(), deviceIdentify.getAppcode())) { // 会诊
                pushNotificationManager = new PushNotificationManager();
                keystore = IosPushService.class.getResourceAsStream(IOS_CERTIFICATE_PATH + IosPushConfig.PUSH_MAJORDOCTOR_FILE);
                pushNotificationManager.initializeConnection(new AppleNotificationServerBasicImpl(keystore, IosPushConfig.PUSH_MAJORDOCTOR_PASSWORD, IosPushConfig.PUSH_MAJORDOCTOR_PUSH_PRODUCTIO));
            } else {
                throw new ErrorCodeException(ErrorCodeConst.GLOBAL_REQUEST_ERROR, String.format("初始化PUSH失败,未定义的AppCode[%s]", deviceIdentify.getAppcode()));
            }

            Device device = new BasicDevice();
            device.setToken(deviceIdentify.getIdentify());
            payLoad.addBadge(pushRequest.getIosBadge());
            PushedNotification notification = pushNotificationManager.sendNotification(device, payLoad, true);

            if (notification.isSuccessful()) {
                response.setCode(ResultEnum.SUCCESS);
            } else {
                response.setCode(ResultEnum.FAILD);
                response.setMsg(notification.getResponse().getMessage());
            }

        } catch (JSONException e) {
            logger.error("IOS push参数错误,req={}", pushRequest);
            logger.error("IOS push数错误", e);
        } catch (CommunicationException e) {
            logger.error("IOS push失败,req={}", pushRequest);
            logger.error("IOS push失败", e);
        } catch (KeystoreException e) {
            logger.error("IOS 证书错误 ,error={}", e.getMessage());
        }

        return response;
    }
}